const express = require('express');
const router = express.Router();
const { spawn } = require('child_process');
const bodyParser = require('body-parser');

router.use(bodyParser.urlencoded({ extended: true }));

// 封装 FFmpeg 推流函数
function ffmpegPushStream(inputFile, outputUrl, resolution, bitrate, fps) {
    const command = [
        '-re',          // 以本地帧率读取输入
        '-i', inputFile,
        '-s', resolution,
        '-b:v', bitrate,
        '-r', String(fps),
        '-c:v', 'libx264',
        '-preset', 'ultrafast',
        '-tune', 'zerolatency',
        '-f', 'flv',
        outputUrl
    ];

    const ffmpegProcess = spawn('ffmpeg', command);

    ffmpegProcess.stdout.on('data', (data) => {
        console.log(`FFmpeg 输出: ${data}`);
    });

    ffmpegProcess.stderr.on('data', (data) => {
        console.error(`FFmpeg 错误: ${data}`);
    });

    ffmpegProcess.on('close', (code) => {
        console.log(`FFmpeg 进程关闭，代码: ${code}`);
    });
}

// 渲染推流参数输入页面
router.get('/', (req, res) => {
    res.render('push', { title: 'PC 端推流参数设置' });
});

// 处理推流请求
router.post('/startPush', (req, res) => {
    const { inputFile, outputUrl, width, height, bitrate, fps } = req.body;

    // 参数验证
    if (!inputFile || !outputUrl || isNaN(width) || isNaN(height) || isNaN(bitrate) || isNaN(fps)) {
        return res.status(400).send('参数错误，请输入有效数值');
    }

    const resolution = `${width}x${height}`;
    const bitrateVal = `${bitrate}k`;

    ffmpegPushStream(inputFile, outputUrl, resolution, bitrateVal, fps);
    res.send('已启动推流，查看控制台获取 FFmpeg 执行详情');
});

module.exports = router;